﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using IdeaNMR.Shared;
using IdeaNMR.Web.Admin;
using IdeaNMR.Web.Core;

namespace IdeaNMR.Web
{
    public partial class NMRDataAdmin : IdeaNMR_BasePage
    {
        #region Page Lifecycle
        protected new void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            if (ScrewTurnWikiFacade.Username != "admin") Response.Redirect("AccessDenied.aspx");
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Master.Title = "NMR Data Administration Tools.";
        }
        #endregion

        #region Event Handlers
        protected void butReinitialize_Click(object sender, EventArgs e)
        {
            panConfirmReinitialize.Visible = true;
        }
        protected void butNoReinitialize_Click(object sender, EventArgs e)
        {
            panConfirmReinitialize.Visible = false;
        }

        // Reinitializes database
        protected void butConfirmReinitialize_Click(object sender, EventArgs e)
        {
            IdeaNMRdbManager.ReInitializeDatabase();
            WikiPagesManager.DeleteAllNMRPages();
            panConfirmReinitialize.Visible = false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks>
        /// Delete temp file at the end
        /// </remarks>
        protected void butUpload_Click(object sender, EventArgs e)
        {
            if (fupData.HasFile)
            {
                string fullPath = ScrewTurnWikiFacade.PublicDirectory + fupData.FileName;
                LogBook<ImportFromLua.LogMessage> ImportLog;
                try
                {
                    fupData.SaveAs(fullPath);
                    string uploadedFile = File.ReadAllText(fullPath);
                    ImportFromLua dbManager = new ImportFromLua(ScrewTurnWikiFacade.PublicDirectory, out ImportLog);

                    dbManager.ImportFromXML(uploadedFile, ScrewTurnWikiFacade.Username);
                    tbLog.Text = FormatLog(ImportLog);
                }
                finally
                {
                    File.Delete(fullPath);
                }
            }
        }
        #endregion

        #region PRIVATE
        private string FormatLog(LogBook<ImportFromLua.LogMessage> Log)
        {
            StringBuilder result = new StringBuilder();
            ImportFromLua.LogMessage msg;
            LogBookEntryType entryType;
            int level;

            result.AppendLine("ERROR SUMMARY");
            result.AppendLine(string.Empty.PadLeft(80, '='));

            if (Log.HasErrors)
            {
                List<ImportFromLua.LogMessage> errors = Log.Errors;
                errors.Sort((x, y) =>
                {
                    return x.Number.CompareTo(y.Number);
                });

                for (int i = 0; i < errors.Count; i++)
                {
                    result.AppendFormat("{0}: {1}\n", errors[i].Number, errors[i].Msg);
                }
            }
            result.AppendLine("\n\n");

            while (Log.HasEntries)
            {
                msg = Log.ReadEntry(out entryType, out level);

                switch (entryType)
                {
                    case LogBookEntryType.Checkpoint:
                        result.AppendLine(string.Empty.PadLeft(3 * level) + msg.Msg.ToUpper());
                        result.AppendLine(string.Empty.PadLeft(80, '='));
                        break;
                    case LogBookEntryType.Status:
                        result.AppendLine(string.Empty.PadLeft(3 * level) + msg.Msg);
                        break;
                    case LogBookEntryType.Error:
                        result.AppendLine(string.Empty.PadLeft(3 * level) + "ERROR! " + msg.Msg);
                        break;
                    default:
                        break;
                }
            }

            return result.ToString();
        }
        #endregion
    }
}